package cn.wmlce.springdatajpademo.web;

import cn.wmlce.springdatajpademo.dao.PersonRespository;
import cn.wmlce.springdatajpademo.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class DataController {

    @Autowired //Spring Data JPA 已自动为你注册bean,所以可自动注入
    private PersonRespository personRespository;

    /**
     * 保存
     *
     * @param name
     * @param address
     * @param age
     * @return
     */
    @RequestMapping("/save")
    public Person save(String name, String address, Integer age) {
        return personRespository.save(new Person(null, name, age, address));
    }

    /**
     * 批量存储
     * @return
     */
    @RequestMapping("/batch/save")
    public List<Person> batchSave() {
        List<Person> personList = new ArrayList<>();
        for (int i = 1; i <= 5; i++){
            personList.add(new Person(null,"yyq"+i,20+i,"FJ"));
        }
        return personRespository.saveAll(personList);
    }

    @RequestMapping("/find1")
    public Person findByNameAndAddress(String name,String address){
        return personRespository.findByNameAndAddress(name,address);
    }

    @RequestMapping("/find2")
    public Person withNameAndAddressQuery(String name,String address){
        return personRespository.withNameAndAddressQuery(name,address);
    }

    @RequestMapping("/find3")
    public Person withNameAndAddressNamedQuery(String name,String address){
        return personRespository.withNameAndAddressNamedQuery(name,address);
    }

    @RequestMapping("/list/person")
    public List<Person> listPersonByAddress(String address) {
        return personRespository.findByAddress(address);
    }

    /**
     * 测试排序
     * @return
     */
    @RequestMapping("/sort")
    public List<Person> sort(){
        return personRespository.findAll(new Sort(Sort.Direction.ASC,"age"));
    }

    /**
     * 测试分页
     * @return
     */
    @RequestMapping("/page")
    public Page<Person> page(){
        return personRespository.findAll(new PageRequest(1,5));
    }
}
